package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.FollowUserDto;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.RealUserListDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.FansUser;
import com.heima.model.user.pojos.FollowUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.FanUserMapper;
import com.heima.user.mapper.FollowUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;

/**
 * @author ybw
 * @version 1.0
 * @date 2021/12/11 18:59
 */
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
  @Autowired private ApUserMapper apUserMapper;
  @Autowired private FollowUserMapper followUserMapper;
  @Autowired private FanUserMapper fanUserMapper;
  @Autowired private RedisTemplate<String, String> redisTemplate;
  /**
   * 用户登录
   *
   * @param loginDto
   * @return
   */
  @Override
  public ResponseResult login(LoginDto loginDto) {
    // 获取参数
    String phone = loginDto.getPhone();
    String password = loginDto.getPassword();
    if (StringUtil.isBlank(phone) && StringUtil.isBlank(password)) {
      // 不登陆，先看看
      String token = AppJwtUtil.getToken(0L);
      return ResponseResult.okResult(token);
    }
    // 校验参数
    if (StringUtil.isBlank(phone)) {
      // 手机号为空
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
    }
    if (StringUtil.isBlank(password)) {
      // 密码为空
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
    }
    // 通过手机号查询数据库
    ApUser apUser = apUserMapper.selectByPhone(phone);
    // 判断是否有值
    if (apUser == null) {
      // 查无此数据
      return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
    }
    // 获取盐
    String salt = apUser.getSalt();
    // 获取数据库中存储的加密密码
    String pwd = apUser.getPassword();
    // 加密
    String str = password + salt;
    String md5pwd = DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8));
    if (!md5pwd.equals(pwd)) {
      // 密码错误
      return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
    // 密码正确，生成token
    String token = AppJwtUtil.getToken(apUser.getId().longValue());
    // 构造返回值对象
    apUser.setSalt("");
    apUser.setPassword("");
    HashMap<Object, Object> map = new HashMap<>();
    map.put("token", token);
    map.put("user", apUser);
    return ResponseResult.okResult(map);
  }

  /**
   * 用户关注
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult follow(FollowUserDto dto) {
    // 参数校验
    if (ObjectUtils.isEmpty(dto)) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    // 获取当前登录用户id
    Integer loginUserId = ApThreadLocalUtil.getUser().getId();
    // 获取参数
    Long articleId = dto.getArticleId();
    Short operation = dto.getOperation();
    Integer authorId = dto.getAuthorId();
    if (operation == 0) {
      // 关注
      // 根据用户id查询用户信息
      ApUser loginUser = apUserMapper.selectById(loginUserId);
      // 新建关注关系表
      FollowUser followUser = new FollowUser();
      followUser.setUserId(loginUserId);
      followUser.setFollowId(authorId);
      followUser.setFollowName(loginUser.getName());
      followUser.setCreatedTime(new Date());
      followUserMapper.insert(followUser);
      // 新建粉丝关系表
      FansUser fansUser = new FansUser();
      fansUser.setUserId(authorId);
      fansUser.setFansId(loginUserId);
      fansUser.setFansName(loginUser.getName());
      fansUser.setCreatedTime(new Date());
      fanUserMapper.insert(fansUser);
      // 新增redis关注信息
      redisTemplate
          .opsForHash()
          .put("USER_BEHAVIOR:FOLLOW:" + loginUserId, authorId.toString(), articleId.toString());

    } else if (operation == 1) {
      // 取消关注
      // 删除关注关系表
      LambdaQueryWrapper<FollowUser> qw1 = new LambdaQueryWrapper<>();
      qw1.eq(FollowUser::getUserId, loginUserId);
      followUserMapper.delete(qw1);
      // 删除粉丝关系表
      LambdaQueryWrapper<FansUser> qw2 = new LambdaQueryWrapper<>();
      qw2.eq(FansUser::getFansId, loginUserId);
      fanUserMapper.delete(qw2);
      // 删除redis关系
      redisTemplate.opsForHash().delete("USER_BEHAVIOR:FOLLOW:" + loginUserId, authorId.toString());
    }

    return ResponseResult.okResult(null);
  }
}
